<div class="layui-body">


    <div style="padding: 16px;">
        <blockquote class="layui-elem-quote layui-text">
            创建新发布
        </blockquote>
        <form class="layui-form layui-form-pane" action="">
            <blockquote class="layui-elem-quote layui-text">
                文章标题
            </blockquote>
            <input type="text" id="text_name" name="textname" placeholder="请输入文章标题" lay-verify="required" class="layui-input">
            <blockquote class="layui-elem-quote layui-text">
                文章内容
            </blockquote>
            <div id="editor—wrapper">
                <div id="toolbar-container"><!-- 工具栏 --></div>
                <div id="editor-container"><!-- 编辑器 --></div>
                <input class="layui-input" type="hidden" name="text" id="get_text">
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">附件管理</label>
                <!-- <button type="button" class="layui-btn layui-btn-normal" id="ID-upload-demo-files">选择文件</button>
                    <button type="button" class="layui-btn" id="ID-upload-demo-files-action">上传</button> -->
                <input type="file" name="file" class="layui-btn" multiple='false' id="ID-upload-demo-form-files">
                <button type="button" class="layui-btn layui-hide" id="ID-upload-demo-btn">
                    <i class="layui-icon layui-icon-upload"></i> 重新上传文件
                </button>
                <label style="width:auto" id="filename" class="layui-form-label"></label>
            </div>
            <blockquote class="layui-elem-quote layui-text">
                因为安全和系统稳定考虑，请将附件内容进行压缩后再上传，压缩格式支持：zip、rar、7z
            </blockquote>
            <div class="layui-form-item">
                <label class="layui-form-label">是否发布</label>
                <div class="layui-input-block">
                    <input type="checkbox" name="status" lay-skin="switch" lay-filter="switchTest" title="是|否">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">同组权限</label>
                <div class="layui-form">
                    <input type="radio" name="gread" value="0" title="不可读写" checked>
                    <input type="radio" name="gread" value="1" title="可读">
                    <input type="radio" name="gread" value="2" title="可读写">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">其他权限</label>
                <div class="layui-form">
                    <input type="radio" name="otherread" value="0" title="不可读写" checked>
                    <input type="radio" name="otherread" value="1" title="可读">
                    <input type="radio" name="otherread" value="2" title="可读写">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" lay-submit lay-filter="demo2">立即提交</button>
                </div>
            </div>
        </form>
    </div>
</div>
<script>
    var loc = location.href;
    var n1 = loc.length; //地址的总长度
    var n2 = loc.indexOf("="); //取得=号的位置
    var text_id = decodeURI(loc.substr(n2 + 1, n1 - n2)); //从=号后面的内容
    layui.use(['form'], function() {
        var form = layui.form;
        var layer = layui.layer;
        var upload = layui.upload;
        var element = layui.element;
        var $ = layui.$;
        var fileid;
        $('#ID-upload-demo-btn').on('click', function() {
            fileid = '';
            layui.layer.msg("重置成功。");
            document.getElementById("filename").textContent = '';
            document.getElementById("ID-upload-demo-btn").classList.add("layui-hide");
            document.getElementById("ID-upload-demo-form-files").classList.remove("layui-hide");
        });
        upload.render({
            elem: '#ID-upload-demo-form-files',
            url: '/admin/api/upload_file.php', // 此处配置上传接口
            accept: 'file',
            exts: 'zip|rar|7z',
            done: function(res) {
                if (res.cod = 1) {
                    layer.msg('上传成功');
                    console.log(res.id);
                    fileid = res.id;
                    document.getElementById("filename").textContent = res.name;
                    document.getElementById("ID-upload-demo-btn").classList.remove("layui-hide");
                    document.getElementById("ID-upload-demo-form-files").classList.add("layui-hide");
                } else {
                    layer.msg('上传失败');
                }
            }
        });
        // 提交事件
        form.on('submit(demo2)', function(data) {
            var field = data.field; // 获取表单字段值
            // console.log(JSON.stringify(field));
            // console.log(editor.getHtml());
            $.ajax({
                url: '/admin/api/selecttext.php',
                data: {
                    'tid':text_id,
                    'textname': field.textname,
                    'main': editor.getHtml(),
                    'status': field.status,
                    'gread': field.gread,
                    'otherread': field.otherread,
                    'moreid': fileid
                },
                contentType: 'application/x-www-form-urlencoded',
                dataType: 'text',
                type: 'post',
                success: function(data) {
                    if (data == "添加成功") {
                        layer.msg(data);
                        setTimeout(function() {
                            location.href = '/admin/metext.php';
                        }, 1000);
                    } else if (data == "参数错误!") {
                        layer.msg(data);
                    } else {
                        layer.msg("未知错误!");
                    }
                }
                // error: function(data) {
                // layer.msg('系统错误');
                // // setTimeout(function() {
                // // location.href = '/admin/useradd.php';
                // // }, 1000);
                // }
            });
            return false; // 阻止默认 form 跳转
        });
    });
    const E = window.wangEditor;
    const {
        createEditor,
        createToolbar
    } = window.wangEditor;

    const editorConfig = {
        placeholder: 'Type here...',
        onChange(editor) {
            const html = editor.getHtml()
            // console.log('editor content', html)
            document.getElementById('get_text').value = html
            // 也可以同步到 <textarea>
        },
        MENU_CONF: {}
    };
    editorConfig.MENU_CONF['uploadImage'] = {
        server: '/admin/api/uploadwe.php',
        timeout: 5 * 1000, // 5s
        fieldName: 'file',
        meta: {
            token: 'xxx',
            a: 100
        },
        metaWithUrl: true, // join params to url
        headers: {
            Accept: 'text/x-json'
        },

        maxFileSize: 50 * 1024 * 1024, // 10M

        base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

        onBeforeUpload(file) {
            console.log('onBeforeUpload', file)

            return file // will upload this file
            // return false // prevent upload
        },
        onProgress(progress) {
            console.log('onProgress', progress)
        },
        onSuccess(file, res) {
            console.log('onSuccess', file, res)
        },
        onFailed(file, res) {
            alert(res.message)
            console.log('onFailed', file, res)
        },
        onError(file, err, res) {
            alert(err.message)
            console.error('onError', file, err, res)
        },
    };
    editorConfig.MENU_CONF['insertVideo'] = {
        onInsertedVideo(videoNode) {
            console.log('inserted video', videoNode)
        },
    };
    editorConfig.MENU_CONF['uploadVideo'] = {
        server: '/admin/api/uploadwes.php',
        timeout: 5 * 1000, // 5s
        fieldName: 'file',
        meta: {
            token: 'xxx',
            a: 100
        },
        metaWithUrl: true, // join params to url
        headers: {
            Accept: 'text/x-json'
        },

        maxFileSize: 100 * 1024 * 1024, // 100M

        onBeforeUpload(file) {
            console.log('onBeforeUpload', file)

            return file // will upload this file
            // return false // prevent upload
        },
        onProgress(progress) {
            console.log('onProgress', progress)
        },
        onSuccess(file, res) {
            console.log('onSuccess', file, res)
        },
        onFailed(file, res) {
            alert(res.message)
            console.log('onFailed', file, res)
        },
        onError(file, err, res) {
            alert(err.message)
            console.error('onError', file, err, res)
        }
    };


    const editor = createEditor({
        selector: '#editor-container',
        html: '<p><br></p>',
        config: editorConfig,
        mode: 'default', // or 'simple'
    });

    const toolbarConfig = {};
    toolbarConfig.excludeKeys = [
        'fullScreen' // 排除菜单组，写菜单组 key 的值即可
    ];

    const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    });


    $(function($) {
        $.get('/admin/api/gettextuid.php', {
            text_id: text_id
        }, function(res) {
            res = JSON.parse(res);
            $('#text_name').val(res.text_name);
            var file_name = document.getElementById("filename");
            file_name.textContent = res.text_file;
            editor.setHtml(res.text_main);
            // console.log(res);
        });
    })
</script>